/**
 * 
 */
package edu.arizona.bio5.onto.decomposition;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import uk.ac.manchester.cs.owlapi.modularity.ModuleType;
import edu.arizona.bio5.onto.decomposition.persistent.ADPersistenceException;
import edu.arizona.bio5.onto.decomposition.persistent.xml.XMLDBPersister;
import edu.arizona.bio5.onto.util.FileUtils;

/**
 * @author Pavel Klinov
 *
 */
public class XMLDBPersistingTaskRunner implements OntologyProcessingTaskRunner {

	private ModuleType m_modType = null;
	private boolean m_labels = true;
	private final String m_dbUri;
	private final String m_user;
	private final String m_pwd;
	private String m_ontologyName = null;
	
	public XMLDBPersistingTaskRunner(ModuleType modType, String dbUri, String user, String pwd) {
		this(modType, true, dbUri, user, pwd);
	}
	
	public XMLDBPersistingTaskRunner(	ModuleType modType,
										boolean labels,
										String dbUri,
										String user,
										String pwd) {		
		m_modType  = modType;
		m_labels = labels;
		m_dbUri = dbUri;
		m_user = user;
		m_pwd = pwd;
	}
	

	@Override
	public void setOntologyFile(File file) {
		m_ontologyName = FileUtils.removeExtension(file);
	}

	@Override
	public void process(OWLOntology ontology, OWLOntologyManager mgr, Writer csvWriter) throws IOException {
		//Decomposition
		if (ontology.getLogicalAxiomCount() > 20000) {
			
			System.out.println("Too big, skipping");
			
			return;
		}
		
		ChiaraDecompositionAlgorithm algo = new ChiaraDecompositionAlgorithm(m_modType); 
		AtomicDecomposition ad = algo.decompose( mgr, ontology );
		//Labeling
		if (m_labels) {

			AtomLabelingAlgorithm labelAlgo = new MSSLabelingAlgorithm();
			
			labelAlgo.compute(ad);
		}
		//Serialize the LAD
		try {
			
			XMLDBPersister persister = new XMLDBPersister(m_dbUri, m_ontologyName, m_user, m_pwd);

			persister.setOntology(ontology);
			persister.persist(ad);
			
		} catch (ADPersistenceException e) {
			e.printStackTrace();
		}
	}
}